package info.fastpace.utils.iterator;

import java.util.Iterator;
import java.util.NoSuchElementException;

public abstract class LazyInitiatorIterator<E> implements Iterator<E> {

	private Object initLock = new Object();
	private Iterator<E> inner;
	private boolean initialized = false;
	
	@Override
	public boolean hasNext() {
		if (!initialized) {
			synchronized (initLock) {
				if (!initialized) {
					inner = createInnerIterator();
					initialized = true;
				}
			}
		}
		if (inner == null) {
			return false;
		}
		
		return inner.hasNext();
	}

	protected abstract Iterator<E> createInnerIterator();

	@Override
	public E next() {
		if (!hasNext()) {
			throw new NoSuchElementException("No more elements");
		}
		return inner.next();
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException("Remove method not supported");
	}
}
